package com.cardone.platform.common.utils;

import lombok.NonNull;

import org.apache.commons.lang3.StringUtils;

import com.cardone.common.dto.TreeEntityDto;
import com.cardone.common.utils.BeanUtils;
import com.cardone.context.ContextHolder;
import com.cardone.context.function.Function2;
import com.cardone.persistent.CommonDtoAttributes;
import com.cardone.platform.common.dto.EntityTreeDto;
import com.cardone.platform.common.service.AssistantService;

/**
 * 实体树工具类
 * 
 * @author yaoht
 * 
 */
public class EntityTreeUtils {
	/**
	 * 保存：实体树
	 * 
	 * @param entity
	 *            实体对象
	 * @param readDictionId
	 *            读取字典标识方法
	 * @return 实体树
	 */
	public static EntityTreeDto saveEntityTree(@NonNull final Object entity,
	        @NonNull final Function2<String, String, String> readDictionId) {
		if (!(entity instanceof TreeEntityDto)) {
			return EntityTreeDto.newEntityTree();
		}

		final TreeEntityDto treeEntity = (TreeEntityDto) entity;

		if (StringUtils.isBlank(treeEntity.getTreeTypeCode()) || StringUtils.isBlank(treeEntity.getTreeCode())) {
			return EntityTreeDto.newEntityTree();
		}

		final String typeId = readDictionId.execution(treeEntity.getTreeTypeCode(), treeEntity.getTreeCode());

		if (StringUtils.isBlank(typeId)) {
			return EntityTreeDto.newEntityTree();
		}

		final EntityTreeDto saveEntityTree = EntityTreeDto.newEntityTree();

		saveEntityTree.setTypeId(typeId);
		saveEntityTree.setEntityId(treeEntity.getId());
		saveEntityTree.setEntityParentId(treeEntity.getParentId());

		BeanUtils.copyProperties(entity, saveEntityTree, CommonDtoAttributes.beginDate.name(), CommonDtoAttributes.endDate.name());

		return ContextHolder.getBean(AssistantService.class).saveEntityTreeByIdOrCode(saveEntityTree);
	}
}